﻿using Assets.XyzCode.Comm;

using System.Collections;

using UnityEngine;

namespace Assets.XyzCode.Fight.Game.Enemy
{
    partial class Enemy_X_Behav
    {
        /** 受伤 Cd */
        private readonly CdTimer _woundCd = new CdTimer(0.5f);

        /** 执行后退携程 */
        private Coroutine _doRecession_XC;

        /// <summary>
        /// 执行受伤
        /// </summary>
        /// <param name="recessionDir">后退方向</param>
        public void DoWound(int recessionDir)
        {
            if (!CanSwitchStateTo(StateEnum.Wound))
            {
                return;
            }

            StopRun();

            if (null != _doRecession_XC)
            {
                StopCoroutine(_doRecession_XC);
            }

            _currState = StateEnum.Wound;
            _woundCd.Reset().Fill();
            _doRecession_XC = StartCoroutine(DoRecession_XC(recessionDir));

            PlayDBAnim("Wound", 1);
        }

        /// <summary>
        /// ( 携程方式 ) 执行后撤
        /// </summary>
        /// <returns>枚举迭代器</returns>
        private IEnumerator DoRecession_XC(int recessionDir)
        {
            if (0 == recessionDir)
            {
                // 如果没有
                _doRecession_XC = null;
                yield break;
            }

            // 规定取值范围
            recessionDir = recessionDir > 0 ? 1 : -1;
            // 移动距离
            float d = 0.32f + Random.Range(-0.1f, +0.3f);
            float speed = 10f + Random.Range(-1f, 3f);

            // 计算目标位置
            Vector3 targetPos = transform.position + Vector3.right * recessionDir * d;

            for (int i = 0; i < 256 && StateEnum.Wound == _currState; i++)
            {
                transform.position = Vector3.Lerp(
                    transform.position, 
                    targetPos, 
                    speed * Time.deltaTime
                );

                if (Mathf.Abs(transform.position.x - targetPos.x) <= 0.01f)
                {
                    // 如果已经非常接近目标位置了,
                    // 直接终止...
                    break;
                }

                yield return 1;
            }

            _doRecession_XC = null;
            yield break;
        }
    }
}
